package com.dms.modules.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.common.api.ApiResponse;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.product.controller.BaseProductController;
import com.dms.modules.user.dto.UserCommentSubmitDTO;
import com.dms.modules.product.vo.CommentVO;
import com.dms.modules.product.service.ProductCommentService;
import com.dms.common.utils.FileUploadUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 用户评论控制器
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/v1/user/comments")
@Api(tags = "用户评价接口")
@PreAuthorize("hasRole('USER')")
public class UserProductCommentController extends BaseProductController {

    @Autowired
    private ProductCommentService commentService;

    @Autowired
    private FileUploadUtils fileUploadUtils;

    @PostMapping
    @ApiOperation("提交评论")
    public ApiResponse<Long> submitComment(@RequestBody @Valid UserCommentSubmitDTO dto) {
        Long userId = getUserId();
        log.info("用户[{}]提交商品[{}]的评论, 订单ID[{}]", userId, dto.getProductId(), dto.getOrderId());
        return ApiResponse.success(commentService.addComment(
            userId,
            dto.getOrderId(),
            dto.getProductId(),
            dto.getContent(),
            dto.getRating(),
            dto.getImages(),
            dto.getIsAnonymous()
        ));
    }

    @GetMapping("/my")
    @ApiOperation("获取我的评论列表")
    public ApiResponse<IPage<CommentVO>> getUserComments(
            @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码不能小于1") Integer pageNum,
            @RequestParam(defaultValue = "10") @Min(value = 1, message = "每页条数不能小于1") Integer pageSize) {
        Long userId = getUserId();
        Page<CommentVO> page = new Page<>(pageNum, pageSize);
        return ApiResponse.success(commentService.getUserComments(userId, page));
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除评论")
    public ApiResponse<Boolean> deleteComment(
            @PathVariable @NotNull(message = "评论ID不能为空") Long id) {
        Long userId = getUserId();
        return ApiResponse.success(commentService.deleteComment(id, userId));
    }

    @PostMapping("/{id}/like")
    @ApiOperation("点赞/取消点赞")
    public ApiResponse<Boolean> toggleLike(
            @PathVariable @NotNull(message = "评论ID不能为空") Long id) {
        Long userId = getUserId();
        return ApiResponse.success(commentService.toggleLike(id, userId));
    }

    @GetMapping("/{id}/detail")
    @ApiOperation("获取评论详情")
    public ApiResponse<CommentVO> getCommentDetail(
            @ApiParam("评论ID") @PathVariable @NotNull(message = "评论ID不能为空") Long id) {
        Long userId = getUserId();
        log.info("用户[{}]获取评论[{}]详情", userId, id);
        return ApiResponse.success(commentService.getCommentDetail(id));
    }

    @PostMapping(value = "/upload/image", consumes = "multipart/form-data")
    @ApiOperation(value = "上传评论图片", notes = "支持jpg、png、gif格式，单个文件最大5MB")
    public ApiResponse<String> uploadCommentImage(
            @ApiParam(value = "图片文件", required = true) @RequestParam("file") MultipartFile file) {
        Long userId = getUserId();
        log.info("用户[{}]上传评论图片", userId);
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return ApiResponse.businessFailed("请选择要上传的文件");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return ApiResponse.businessFailed("只能上传图片文件");
            }

            // 使用FileUploadUtils上传到OSS，指定目录为comments/images
            String imageUrl = fileUploadUtils.uploadFile(file, "comments/images");
            return ApiResponse.success(imageUrl);
        } catch (Exception e) {
            log.error("上传评论图片失败: {}", e.getMessage(), e);
            return ApiResponse.businessFailed("上传失败：" + e.getMessage());
        }
    }

} 

// @PostMapping("/{id}/reply")
// @ApiOperation("回复评论")
// public ApiResponse<Boolean> replyComment(
//         @PathVariable @NotNull(message = "评论ID不能为空") Long id,
//         @RequestParam @NotNull(message = "回复内容不能为空") String content) {
//     Long userId = getUserId();
//     return ApiResponse.success(commentService.replyComment(id, content, userId));
// }